问题描述(难度简单-581)
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
1 | Input: [2, 6, 4, 8, 10, 9, 15] |
Note:
- Then length of the input array is in range [1, 10,000].
- The input array may contain duplicates, so ascending order here means <=.
方法一:sort+循环
直接复制一个数组出来,排序完了之后比较排序和非排序数组。时间复杂度O(NlogN),空间复杂度O(N)。
1 | package P581; |
方法二:两边遍历
从前往后找到比前面最大值还要小的值,从后往前找到比之前最小值还要大的值,即为边界值。时间复杂度O(N),空间复杂度O(1)。
1 | package P581; |